package com.finance.report.service;

import com.finance.base.constant.BaseConstants;
import com.finance.base.exception.BaseException;
import com.finance.framework.file.FileUtils;
import com.finance.report.bean.export.ManLogisticsParse;
import com.finance.report.bean.export.ManLogisticsParseBean;
import com.finance.report.bean.pojo.LogisticsComittedInfos;
import com.finance.report.bean.pojo.LogisticsCommitted;
import com.finance.report.bean.pojo.ManLogistics;
import com.finance.report.dao.ManSalaryMapper;
import com.finance.util.export.ExportBuilder;
import com.finance.util.export.ExportFactory;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * @Author: gly
 * @Date: Created in 2017/05/04
 */
@Service
public class TimerManSalaryService implements ITimerManSalaryService {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private ILogisticsExtendService logisticsExtendService;
    @Autowired
    private ManSalaryMapper manSalaryMapper;

    @Override
    @Transactional
    public void upload(String salaryMonth) {
        this.logger.info("开始生成{}配费明细",salaryMonth);
        String suffix ="";
        if(StringUtils.isNotBlank(salaryMonth)) {
            suffix= salaryMonth.trim().replace("-", "").substring(2, 6);
        }else{
            throw new BaseException(BaseConstants.ERR_INVALID_PARAMETER);
        }
        String extendTableName = BaseConstants.SYSCONFIG_KEY_LOGISTICS_EXTEND_TABLE + suffix;
        if(logisticsExtendService.isFinished(extendTableName)){
            return;
        }
        List<String> postmanNos = logisticsExtendService.getPostmans(extendTableName);
        String tableName = BaseConstants.SYSCONFIG_KEY_LOGISTICDATA_TABLE+suffix;
        Iterator<String> iterator =postmanNos.iterator();
        String postmanNo = "";
        while (iterator.hasNext()) {
            postmanNo = iterator.next();
            if("21".equals(postmanNo)){
                continue;
            }
            this.logger.info("开始生成配送员:{},月份为:{}配费明细",new Object[]{postmanNo,salaryMonth});
            List<LogisticsCommitted> logisticsCommitteds = logisticsExtendService.getManLogistics(extendTableName,postmanNo);
            if(logisticsCommitteds!=null && logisticsCommitteds.size()>0) {
                List<ManLogistics>  manLogisticList =new ArrayList<ManLogistics>();
                for(LogisticsCommitted  logisticsCommitted:logisticsCommitteds) {
                    LogisticsComittedInfos logisticsComittedInfos = logisticsExtendService.getLogisticsInfo(tableName,logisticsCommitted.getWaybillNum());
                    ManLogistics manLogistics= new ManLogistics();
                    try {
                        BeanUtils.copyProperties(logisticsCommitted,manLogistics);
                        BeanUtils.copyProperties(logisticsComittedInfos,manLogistics);
                    } catch (Exception e) {
                        throw new BaseException(BaseConstants.ERR_COPYBEAN);
                    }
                    manLogisticList.add(manLogistics);
                }
                String pathName = getClass().getResource("/").getFile().toString();
                pathName += salaryMonth +"-"+ postmanNo + BaseConstants.DEFAULT_EXPORT_FILE_SUFFIX;
                File file = new File(pathName);
                try {
                    ExportBuilder builder = new ExportBuilder(ManLogisticsParseBean.class, new ManLogisticsParse());
                    ExportFactory factory = ExportFactory.getExportFactory(builder);
                    factory.setDataList(manLogisticList).outPut(file);
                    FileUtils.uploadFile(BaseConstants.FINANCE_REPORT_FILE_PATH, file.getName(), file);
                } catch (Exception e) {
                    logger.error(e.getMessage(),e);
                    this.logger.error("配送员:{},{}配费明细生成失败 原因:{}",new Object[]{postmanNo,salaryMonth,e.getMessage()});
                } finally {
                    if (file != null) {
                        file.delete();
                    }
                }
            }
        }
        this.logger.info("{}所有配送员配费明细文件生成完成",salaryMonth);
    }

    @Override
    @Transactional
    public void del(String month) {
        boolean result1 = manSalaryMapper.delSalaryByMonth(month) > 0;
        boolean result2 = manSalaryMapper.delSalaryDetailByMonth(month) > 0;
        this.logger.info("月报数据已清除 {} 结果：{}",new Date().toString(),String.valueOf(result1 && result2));
    }
}

